<template>
  <div class="app-container">
    <div class="header">
      <div class="header-first" style="overflow: hidden;">
        <div style="float: left;font-size: 24px;font-weight: 500;">{{ title }}</div>
        <div style="float: right;">
          <el-button @click.stop="cancelSave">取消</el-button>
          <el-button type="primary" @click.stop="save">保存</el-button>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="header-form">
        <el-form-item label="业务对象名称" class="header-form-item" prop="businessObjectName">
          <el-input v-model="form.businessObjectName" placeholder="请输入业务对象名称" style="width: 240px;"></el-input>
        </el-form-item>
        <el-form-item label="业务对象标识" class="header-form-item" prop="businessObjectFlag">
          <el-input v-model="form.businessObjectFlag" placeholder="请输入业务对象标识" style="width: 240px;"></el-input>
        </el-form-item>
        <el-form-item label="系统平台" class="header-form-item" prop="sysPlatform">
          <el-select v-model="form.sysPlatform" placeholder="请选择系统平台" disabled>
            <el-option label="序列号追溯系统" value="01"></el-option>
            <el-option label="金蝶云星空" value="02"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" class="header-form-item" prop="businessType">
          <el-radio-group v-model="form.businessType">
            <el-radio v-for="dict in dict.type.business_type" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="业务对象描述" class="header-form-item">
          <el-input v-model="form.businessObjectDesc" type="textarea" placeholder="请输入" style="width: 240px;"></el-input>
        </el-form-item>
        <el-form-item label="是否有更新标识" class="header-form-item" label-width="120px" prop="hasUpdateFlag">
          <el-radio-group v-model="form.hasUpdateFlag">
            <el-radio v-for="dict in dict.type.has_update_flag" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

    </div>
    <div class="content">
      <div style="height: 60px;">
        <div style="float: left;font-size: 20px;">字段设置</div>
        <el-button @click="openImportTable" style="float: left;margin: 0 20px;">导入表</el-button>
      </div>
      <div>
        <el-button type="primary" plain @click.stop="add">新增</el-button>

        <el-table :data="tableData" style="width: 100%; margin-top: 17px" border>

          <el-table-column label="字段列名" prop="columnName" min-width="120px" :show-overflow-tooltip="true">
            <template slot-scope="{ row }">
              <el-input v-if="row.$isEdit" v-model="row.columnName" placeholder="请输入字段列名"></el-input>
              <span v-else>{{ row.columnName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="字段描述" min-width="120px">
            <template slot-scope="{ row }">
              <el-input v-if="row.$isEdit" v-model="row.columnComment" placeholder="请输入字段描述"></el-input>
              <span v-else>{{ row.columnComment }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物理类型" prop="columnType" min-width="120px" :show-overflow-tooltip="true">
            <template slot-scope="{ row }">
              <el-input v-if="row.$isEdit" v-model="row.columnType" placeholder="请输入物理类型"></el-input>
              <span v-else>{{ row.columnType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Java类型" min-width="120px">
            <template slot-scope="{ row }">
              <el-select v-if="row.$isEdit" v-model="row.javaType" placeholder="请选择Java类型">
                <el-option label="Long" value="Long" />
                <el-option label="String" value="String" />
                <el-option label="Integer" value="Integer" />
                <el-option label="Double" value="Double" />
                <el-option label="BigDecimal" value="BigDecimal" />
                <el-option label="Date" value="Date" />
                <el-option label="Boolean" value="Boolean" />
              </el-select>
              <span v-else>{{ row.javaType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="java属性" min-width="120px">
            <template slot-scope="{ row }">
              <el-input v-if="row.$isEdit" v-model="row.javaField" placeholder="请输入java属性"></el-input>
              <span v-else>{{ row.javaField }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否为主键" min-width="120px">
            <template slot-scope="scope">
              <el-switch v-if="scope.row.$isEdit" v-model="scope.row.isPrimaryKey" :active-value="0"
                :inactive-value="2"></el-switch>
              <span v-else>{{ scope.row.isPrimaryKey === 0 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否为外键" min-width="120px">
            <template slot-scope="scope">
              <el-switch v-if="scope.row.$isEdit" v-model="scope.row.isForeignKey" :active-value="0"
                :inactive-value="2"></el-switch>
              <span v-else>{{ scope.row.isForeignKey === 0 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="外键列名" prop="foreignName" min-width="120px" :show-overflow-tooltip="true">
            <template slot-scope="{ row }">
              <el-input v-if="row.$isEdit" v-model="row.foreignName" placeholder="请输入外键列名"></el-input>
              <span v-else>{{ row.foreignName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="关联表" prop="associationTable" min-width="120px">
            <template slot-scope="{ row }">
              <div class="closeable" @click.stop="handleSelectColumn(row)">
                <el-input :disabled="!row.$isEdit" v-model="row.associationTable"
                  suffix-icon="el-icon-more el-input__icon">
                  <i slot="suffix" style="position: absolute;
                        right: -16px;
                        top: -18px;" class="el-input__icon el-icon-error" v-if="row.$isEdit"
                    @click.stop="removeMapping(row)" />
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200px">
            <template slot-scope="{ row, $index }">
              <el-button type="danger" plain size="mini" @click="deleteData(row, $index)">删除</el-button>

              <el-button v-if="row.$isEdit" type="primary" plain size="mini"
                @click.stop="confirmSubmit(row)">确认</el-button>

              <el-button v-else type="primary" plain size="mini" @click.stop="edit($index)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <SelectAssociationTable :andsysPlatform="this.form.sysPlatform" v-if="openSelectColumnDialog"
          :show.sync="openSelectColumnDialog" label="列名" formTitle="选择关联表" primaryKey="id"
          :businessObjectId="currentReceiverObjectId" :id="currentReceiverId" @closeSelectColumn="closeSelectColumn"
          showField="columnComment" @selectDialogItem="selectDialogItem">
        </SelectAssociationTable>
      </div>
    </div>
    <SelectTable v-if="openImportTableDialog" ref="import" @getGenTable="getGenTable" />
  </div>
</template>
<script>
import { getGenTable } from "@/api/tool/gen";
import SelectTable from "@/views/interfaceConfig/businessObject/components/SelectTable";
import SelectAssociationTable from "@/views/interfaceConfig/businessObject/components/SelectAssociationTable";
import { addBusinessObject, updateBusinessObject, getBusinessObject, updateBusinessFieldSettingIsPrimaryKey } from "@/api/interfaceConfig/businessObject/businessObject.js";

export default {
  name: 'AddOrUpdateBusinessObject',
  dicts: ['business_type', 'has_update_flag'],
  components: { SelectTable, SelectAssociationTable },
  data() {
    return {
      title: '',
      tableData: [],
      fieldMappingData: [],
      openImportTableDialog: false,
      currentReceiverObjectId: undefined,
      openSelectColumnDialog: false,
      businessId: undefined,
      form: {},
      rules: {
        businessObjectName: [
          { required: true, message: "业务对象名称不能为空", trigger: "blur" }
        ],
        businessObjectFlag: [
          { required: true, message: "业务对象标识不能为空", trigger: "blur" }
        ],
        sysPlatform: [
          { required: true, message: "系统平台不能为空", trigger: "blur" }
        ],
        businessType: [
          { required: true, message: "业务类型不能为空", trigger: "change" }
        ],
        hasUpdateFlag: [
          { required: true, message: "是否有更新标识不能为空", trigger: "blur" }
        ]
      }
    }
  },
  mounted() {
    this.businessId = this.$route.query && this.$route.query.businessId
    let sysPlatform = this.$route.query && this.$route.query.sysPlatform
    this.title = this.businessId ? '编辑业务对象' : '新增业务对象'
    if (this.businessId) this.init()
    this.form.sysPlatform = sysPlatform || ''
  },
  methods: {
    handleSelectColumn(row) {
      console.log(row);
      //编辑模式才打开弹窗
      if (row.$isEdit) {
        this.currentReceiverObjectId = this.form.sysObjId1
        this.currentReceiverId = row.id
        this.openSelectColumnDialog = true
      }
    },
    closeSelectColumn() {
      this.currentReceiverObjectId = undefined
      this.openSelectColumnDialog = false
    },
    selectDialogItem(Id, row) {
      let { id, businessObjectName, businessObjectFlag } = row;
      // 找到tableData中id为Id的元素（注意这里将receiverId更改为Id）  
      const targetIndex = this.tableData.findIndex(item => item.id === Id);
      // 数组fieldMappingData移除id为Id的元素（注意这里检查item.id而不是item.receiverId）  
      const mappingIndex = this.fieldMappingData.findIndex(item => item.id === Id);
      if (mappingIndex !== -1) {
        this.fieldMappingData.splice(mappingIndex, 1); // 移除找到的元素  
      }
      if (targetIndex !== -1) {
        // 更新tableData中对应的元素属性  
        this.tableData[targetIndex].associationTable = id;

        // 将id添加到fieldMappingData数组中（注意这里保持键名的一致性）  
        this.fieldMappingData.push({ syncerId: id, id: Id }); // 如果Id和id应该相同，则可能只需要一个  
        // 或者，如果您想保持键名为小写，并且Id和id是不同的，那么可以保留这样  
      }
    },
    //点击x移除映射
    removeMapping(row) {
      const targetIndex = this.tableData.findIndex(item => item.id === row.id);
      //数组fieldMappingData移除为receiverId的元素
      const mappingIndex = this.fieldMappingData.findIndex(item => item.id === row.id);
      if (mappingIndex !== -1) {
        this.fieldMappingData.splice(mappingIndex, 1)
      }

      if (targetIndex !== -1) {
        // 更新tableData中对应的元素属性
        this.tableData[targetIndex].associationTable = undefined;
      }
    },
    init() {
      getBusinessObject(this.businessId).then(response => {
        let { id, businessObjectName, businessObjectFlag, sysPlatform, businessType, businessObjectDesc, hasUpdateFlag } = response.data
        this.form = {
          id, businessObjectName, businessObjectFlag, sysPlatform, businessType, businessObjectDesc, hasUpdateFlag
        };
        this.tableData = response.data['businessFieldSettings']
      });
    },
    edit(i) {
      this.$set(this.tableData[i], "$isEdit", true);
    },
    // 确认提交
    confirmSubmit(row) {
      if (!row.columnName || !row.columnComment || !row.columnType || !row.javaType || !row.javaField || !row.columnComment) return this.$message.error("不能为空");

      row.$isEdit = !row.$isEdit;
    },
    // 删除数据
    // 分前端和请求接口删除
    deleteData(row, i) {
      if (row.$isEdit) {
        this.tableData.splice(i, 1);
      } else {
        console.log("向后端发请求");
      }
    },
    // 新增输入框数据字段
    add() {
      this.tableData.push({
        id: "",
        columnName: "",
        columnComment: "",
        columnType: "",
        javaType: "",
        javaField: "",
        $isEdit: true,
      });
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.openImportTableDialog = true
      this.$nextTick(() => {
        this.$refs.import.show();
      })
    },
    getGenTable(tableId) {
      // 获取表详细信息
      getGenTable(tableId).then(res => {
        this.tableData = res.data.rows;
        this.openImportTableDialog = false
      });
    },
    cancelSave() {
      const obj = { path: "/interfaceConfig/BusinessObject" };
      this.$tab.closeOpenPage(obj);
    },
    save() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //更新操作
            updateBusinessObject({
              ...this.form,
              businessFieldSettings: this.tableData
            }).then(resp => {
              this.$modal.msgSuccess("更新成功")
              //重新路由会原页面
              this.cancelSave()
            }).catch(() => {
              this.$modal.msgError('更新成功')
            })
          } else {
            //新增操作
            addBusinessObject({
              ...this.form,
              businessFieldSettings: this.tableData
            }).then(resp => {
              this.$modal.msgSuccess("保存成功")
              //重新路由会原页面
              this.cancelSave()
            }).catch(() => {
              this.$modal.msgError('保存失败')
            })
          }
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.header {
  border: 1px solid #d5d4d4;
  padding: 10px;
  box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.3);

  .header-first {
    height: 68px;
    line-height: 68px;

  }

  .header-form {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .header-form-item {
    display: inline-block;
  }
}

.content {
  border: 1px solid #d5d4d4;
  padding: 10px;
  box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.3);
  margin-top: 10px;
}
</style>
